package com.sisyphus.tron;


import android.os.Parcel;
import android.os.Parcelable;

import org.spongycastle.util.encoders.Hex;
import org.tron.common.crypto.ECKey;
import org.tron.common.crypto.Hash;
import org.tron.common.utils.Base58;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.Utils;

import java.math.BigInteger;



/**
 * 允许您在hex/base58和TRON的私钥表示之间进行转换
 */
public class Account implements Parcelable {

    private String name;

    private String address;

    private String publicKey;

    private String privateKey;


    Account() {
        ECKey ecKey = new ECKey(Utils.getRandom());

        this.address = TronAndroid.encode58Check(ecKey.getAddress());
        this.publicKey = ByteArray.toHexString(ecKey.getPubKey());
        this.privateKey = Hex.toHexString(ecKey.getPrivKeyBytes());
    }

    Account(String name, String privateKey) {
        this.name = name;

        ECKey ecKey = ECKey.fromPrivate(new BigInteger(privateKey, 16));

        this.privateKey = privateKey;
        this.address = TronAndroid.encode58Check(ecKey.getAddress());
        this.publicKey = ByteArray.toHexString(ecKey.getPubKey());
    }

    protected Account(Parcel in) {
        name = in.readString();
        address = in.readString();
        publicKey = in.readString();
        privateKey = in.readString();
    }

    public static final Creator<Account> CREATOR = new Creator<Account>() {
        @Override
        public Account createFromParcel(Parcel in) {
            return new Account(in);
        }

        @Override
        public Account[] newArray(int size) {
            return new Account[size];
        }
    };

    public String getAddress() {
        return address;
    }

    public String getPublicKey() {
        return publicKey;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "{" +
                "address='" + address + '\'' +
                ", privateKey='" + privateKey + '\'' +
                ", publicKey='" + publicKey + '\'' +
                '}';
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(name);
        parcel.writeString(address);
        parcel.writeString(publicKey);
        parcel.writeString(privateKey);
    }
}
